-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.c
38 lines (31 loc) · 812 Bytes
/
Solution.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <stdio.h>
#include <string.h>
char* longestCommonPrefix(char arr[][100], int n) {
static char prefix[100];
strcpy(prefix, arr[0]);
for (int i = 1; i < n; i++) {
int j = 0;
while (arr[i][j] && prefix[j] && arr[i][j] == prefix[j]) {
j++;
}
prefix[j] = '\0'; // Terminate the prefix string
}
return prefix;
}
int main() {
int n;
printf("Enter the number of strings: ");
scanf("%d", &n);
char arr[n][100];
printf("Enter %d strings:\n", n);
for (int i = 0; i < n; i++) {
scanf("%s", arr[i]);
}
char* result = longestCommonPrefix(arr, n);
if (strlen(result) > 0) {
printf("Longest Common Prefix: %s\n", result);
} else {
printf("No common prefix.\n");
}
return 0;
}